// 发帖页面功能
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('createPostForm');
    const titleInput = document.getElementById('title');
    const contentInput = document.getElementById('content');
    const titleCount = document.getElementById('titleCount');
    const contentCount = document.getElementById('contentCount');
    const imageUploadArea = document.getElementById('imageUploadArea');
    const imageInput = document.getElementById('imageInput');
    const imagePreview = document.getElementById('imagePreview');
    const loadingOverlay = document.getElementById('loadingOverlay');

    let uploadedImages = [];

    // 字符计数功能
    function updateCharCount(input, countElement, maxLength = null) {
        const length = input.value.length;
        countElement.textContent = length;
        
        if (maxLength) {
            if (length > maxLength * 0.9) {
                countElement.style.color = '#e74c3c';
            } else if (length > maxLength * 0.7) {
                countElement.style.color = '#f39c12';
            } else {
                countElement.style.color = '#666';
            }
        }
    }

    titleInput.addEventListener('input', () => {
        updateCharCount(titleInput, titleCount, 100);
    });

    contentInput.addEventListener('input', () => {
        updateCharCount(contentInput, contentCount);
    });

    // 图片上传功能
    imageUploadArea.addEventListener('click', () => {
        imageInput.click();
    });

    imageUploadArea.addEventListener('dragover', (e) => {
        e.preventDefault();
        imageUploadArea.style.borderColor = '#4a90e2';
        imageUploadArea.style.background = '#f0f8ff';
    });

    imageUploadArea.addEventListener('dragleave', (e) => {
        e.preventDefault();
        imageUploadArea.style.borderColor = '#ddd';
        imageUploadArea.style.background = '#fafafa';
    });

    imageUploadArea.addEventListener('drop', (e) => {
        e.preventDefault();
        imageUploadArea.style.borderColor = '#ddd';
        imageUploadArea.style.background = '#fafafa';
        
        const files = e.dataTransfer.files;
        handleImageFiles(files);
    });

    imageInput.addEventListener('change', (e) => {
        handleImageFiles(e.target.files);
    });

    function handleImageFiles(files) {
        const maxImages = 5;
        const maxSize = 5 * 1024 * 1024; // 5MB
        const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png'];

        if (uploadedImages.length + files.length > maxImages) {
            alert(`最多只能上传${maxImages}张图片`);
            return;
        }

        Array.from(files).forEach(file => {
            // 检查文件类型
            if (!allowedTypes.includes(file.type)) {
                alert('只支持 JPG、PNG 格式的图片');
                return;
            }

            // 检查文件大小
            if (file.size > maxSize) {
                alert('图片大小不能超过 5MB');
                return;
            }

            // 创建预览
            const reader = new FileReader();
            reader.onload = (e) => {
                const imageUrl = e.target.result;
                uploadedImages.push({
                    file: file,
                    url: imageUrl
                });
                updateImagePreview();
            };
            reader.readAsDataURL(file);
        });
    }

    function updateImagePreview() {
        imagePreview.innerHTML = '';
        
        uploadedImages.forEach((image, index) => {
            const imageItem = document.createElement('div');
            imageItem.className = 'image-item';
            
            imageItem.innerHTML = `
                <img src="${image.url}" alt="预览图片">
                <button type="button" class="remove-btn" onclick="removeImage(${index})">
                    <i class="fas fa-times"></i>
                </button>
            `;
            
            imagePreview.appendChild(imageItem);
        });

        // 更新上传区域显示
        if (uploadedImages.length > 0) {
            imageUploadArea.style.display = 'none';
        } else {
            imageUploadArea.style.display = 'block';
        }
    }

    // 移除图片
    window.removeImage = function(index) {
        uploadedImages.splice(index, 1);
        updateImagePreview();
    };

    // 表单提交
    form.addEventListener('submit', async (e) => {
        e.preventDefault();

        // 显示加载状态
        loadingOverlay.style.display = 'flex';

        try {
            // 获取表单数据
            const formData = new FormData(form);
            const postData = {
                title: formData.get('title').trim(),
                content: formData.get('content').trim(),
                post_type: formData.get('post_type'),
                category: formData.get('category'),
                video_url: formData.get('video_url') || null,
                tags: formData.get('tags') || null,
                image_urls: uploadedImages.map(img => img.url) // 这里应该上传到服务器并返回URL
            };

            // 验证数据
            if (!postData.title || !postData.content || !postData.post_type || !postData.category) {
                throw new Error('请填写所有必填项');
            }

            // 获取用户token
            const token = localStorage.getItem('token') || sessionStorage.getItem('token');
            if (!token) {
                throw new Error('请先登录');
            }

            // 发送请求
            console.log('发送请求到:', '/api/posts');
            console.log('请求数据:', postData);
            console.log('Token:', token ? '存在' : '不存在');
            
            const response = await fetch('/api/posts', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify(postData)
            });

            console.log('响应状态:', response.status);
            console.log('响应头:', response.headers);

            // 检查响应状态
            if (!response.ok) {
                const errorText = await response.text();
                console.error('服务器错误响应:', errorText);
                throw new Error(`服务器错误 (${response.status}): ${errorText}`);
            }

            // 尝试解析JSON
            let result;
            try {
                const responseText = await response.text();
                console.log('响应内容:', responseText);
                result = JSON.parse(responseText);
            } catch (parseError) {
                console.error('JSON解析失败:', parseError);
                throw new Error('服务器返回的数据格式错误');
            }

            if (result.success) {
                // 发布成功
                alert('帖子发布成功！');
                window.location.href = 'forum.html';
            } else {
                throw new Error(result.message || '发布失败');
            }

        } catch (error) {
            console.error('发布帖子失败:', error);
            alert(error.message || '发布失败，请稍后重试');
        } finally {
            // 隐藏加载状态
            loadingOverlay.style.display = 'none';
        }
    });

    // 检查登录状态
    function checkLoginStatus() {
        const token = localStorage.getItem('token') || sessionStorage.getItem('token');
        if (!token) {
            alert('请先登录');
            window.location.href = 'login.html';
            return false;
        }
        return true;
    }

    // 页面加载时检查登录状态
    if (!checkLoginStatus()) {
        return;
    }

    // 初始化字符计数
    updateCharCount(titleInput, titleCount, 100);
    updateCharCount(contentInput, contentCount);
}); 